import difflib

from django.http import JsonResponse
from django.shortcuts import render
from .spider import rumor_spider

def is_simlary(x, y):
    sim = difflib.SequenceMatcher(None, x, y).quick_ratio()
    return True if sim > 0.9 else False

def compute_similarity(x, y):
    return difflib.SequenceMatcher(None, x, y).quick_ratio()

# Create your views here.
def index(request):
    if request.method == 'GET':
        return render(request, 'index.html')

    elif request.method == 'POST':
        keyword = request.POST.get('keyword')
        if keyword:
            results = rumor_spider(keyword)
            value = 0
            similarity = 0
            max_value = 0
            max_similarity = 0
            if results:
                for result in results:
                    similarity = compute_similarity(result['title'], keyword)
                    if similarity >= 0.9:
                        value = 100
                    elif similarity >= 0.8:
                        value = 80
                    elif similarity >= 0.6:
                        value = 60
                    elif similarity >= 0.1:
                        value = 10
                    else:
                        value = 0

                    if value > max_value:
                        max_value = value

                    if similarity > max_similarity:
                        max_similarity = similarity

                if len(results) == 1:
                    max_value = 100
            else:
                max_value = 0
            return render(request, 'index.html', context={'content': keyword, 'value': max_value, 'results': results})
        else:
            return render(request, 'index.html')

